/*
 * @lc app=leetcode.cn id=92 lang=java
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if ( left == right){
            return head;
        }
        ListNode beforeHead = new ListNode(0);
        beforeHead.next = head;
        ListNode p = beforeHead;
        ListNode q = beforeHead.next;
        int num = 0;
        ListNode item = null;
        while ( q.next != null){
            if ( ++num < left){
                p = p.next;
                q = q.next;
            }else {
                item = q.next;
                q.next = item.next;
                item.next = p.next;
                p.next = item;
            }
            if ( num > right-left){
                break;
            }
        }
        return beforeHead.next;
    }
}
// @lc code=end

